package org.example.lotterysystem.service.impl;

import org.example.lotterysystem.common.errorcode.ErrorCodeConstants;
import org.example.lotterysystem.common.errorcode.GlobalErrorCodeConstants;
import org.example.lotterysystem.common.exception.ServiceException;
import org.example.lotterysystem.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@Service
public class PictureServiceImpl implements PictureService {

    @Value("${pic.local-path}")
    private String localPath;

    /**
     *保存图片
     */
    @Override
    public String savePicture(MultipartFile multipartFile) {
        //创建目录
        File file=new File(localPath);
        if(!file.exists()){
            file.mkdir();
        }

        //创建索引
        String filename = multipartFile.getOriginalFilename();
        if(filename==null){
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR);
        }
        String suffix=filename.substring(filename.lastIndexOf("."));
        filename= UUID.randomUUID()+suffix;

        //保存图片
        try{
            multipartFile.transferTo(new File(localPath+"/"+filename));
        }catch (Exception e){
            throw new ServiceException(ErrorCodeConstants.PIC_UPLOAD_ERROR);
        }

        return filename;
    }
}
